package cn.qiyu5522.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.constant.SystemConstants;
import cn.qiyu5522.domain.entity.LoginUser;
import cn.qiyu5522.domain.entity.SystemException;
import cn.qiyu5522.domain.entity.User;
import cn.qiyu5522.enums.AppHttpCodeEnum;
import cn.qiyu5522.service.MenuService;
import cn.qiyu5522.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * ClassName: UserDetialServiceImpl
 * Package: cn.qiyu5522.service.impl
 * Description:
 *
 * @Author: Tonkey
 * @Create：2024/4/17-8:39
 * @Version: v1.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        queryWrapper.eq(User::getUserName,username);
        User user = userService.getOne(queryWrapper);
        // 判断是否查询出用户，没有则抛异常
        if(!ObjectUtil.isNotEmpty(user)){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_EXIST);
        }
        // 后后端管理员用户登录
        if(SystemConstants.ADMIN_USER.equals(user.getType())){
            List<String> strings = menuService.selectPermsByUserId(user.getId());
            return new LoginUser(user,strings);
        }
        // 返回用户信息  普通用户无权限
        LoginUser loginUser = new LoginUser(user,null);
        return loginUser;
    }
}
